package ext.generic.part;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.util.LocalizableMessage;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;

import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.DynamicRefreshInfo;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.util.misc.NmContext;

/**
 *该类主要处理用户在CAD图档签审流程中的“更新过期随签对象”的请求
 */
public class RenewReviewObjectsFormProcessor extends DefaultObjectFormProcessor
{
    private static final String RESOURCE = "com.ptc.netmarkets.util.utilResource";
    private static final Logger log;
    protected String redirectURL;
    private static boolean VERBOSE = false;
    private static String CLASSNAME = RenewReviewObjectsFormProcessor.class.getName();

    static
    {
        try
        {
            log = LogR.getLogger(ext.generic.part.RenewReviewObjectsFormProcessor.class.getName());
            VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.generic.part.verbose", false);
        }
        catch (Exception exception)
        {
            throw new ExceptionInInitializerError(exception);
        }
    }

    public RenewReviewObjectsFormProcessor()
    {
        redirectURL = null;
    }

    /**
     *更新过期随签对象的具体方法
     */
    public FormResult doOperation(NmCommandBean nmcommandbean, List list) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doOperation()");
        //Vector reviewObjs = new Vector();
        List reviewObjs = new ArrayList();
        java.util.Locale locale = SessionHelper.getLocale();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        if (nmcommandbean.getSelected().size() == 0)
        {
            FeedbackMessage feedbackmessage =
                new FeedbackMessage(FeedbackType.FAILURE, locale, new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null), null, new LocalizableMessage[]
                    { new WTMessage("com.ptc.netmarkets.util.utilResource", "NO_OBJECT_SELECTED", null) });
            formresult.addFeedbackMessage(feedbackmessage);
            formresult.setStatus(FormProcessingStatus.FAILURE);
            formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
            return formresult;
        }
        wt.fc.Persistable persistable = nmcommandbean.getPrimaryOid().getWtRef().getObject();
        if (persistable instanceof WorkItem)
        {
            WorkItem workItem = (WorkItem) persistable;
            WfAssignedActivity wfAssignedActivity = (WfAssignedActivity) workItem.getSource().getObject();
            reviewObjs =  (List) (wfAssignedActivity.getContext().getValue("reviewObjs"));
            //add by sean 2013.1.12 解决随签表拥有重复的主对象
            WTPart pbo = (WTPart) (wfAssignedActivity.getContext().getValue("primaryBusinessObject"));
            String pboIdentity = pbo.getIdentity();
            int temp =0;
            for(int i=0;i<reviewObjs.size();i++){
            	String identity = ((ObjectReference)(reviewObjs.get(i))).getObject().getIdentity();
            	if(identity.equals(pboIdentity)){
            		temp++;
            	}
            	if(temp>1){
            		reviewObjs.remove(i);
            	}
            }
            boolean flag = doRenewOperation(nmcommandbean, reviewObjs);
            if (flag)
            {
                wfAssignedActivity.getContext().setValue("reviewObjs", reviewObjs);
                PersistenceHelper.manager.save(wfAssignedActivity);
            }
        }
        formresult.setNextAction(FormResultAction.REFRESH_CURRENT_PAGE);
        super.doOperation(nmcommandbean, list);
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doOperation()");
        return formresult;
    }

    protected FormResult setRefreshInfo(FormResult formresult, NmCommandBean nmcommandbean, List list) throws WTException
    {
        DynamicRefreshInfo dynamicrefreshinfo = new DynamicRefreshInfo();
        dynamicrefreshinfo.setLocation(nmcommandbean.getActionOid());
        dynamicrefreshinfo.setOid(nmcommandbean.getActionOid());
        NmCommandBean _tmp = nmcommandbean;
        dynamicrefreshinfo.setAction("U");
        formresult.addDynamicRefreshInfo(dynamicrefreshinfo);
        return formresult;
    }

    /**
     *更新所选对象:如果所选对象不是最新版本，则获取最新版本，请更新至随签对象列表中
     */
    public static boolean doRenewOperation(NmCommandBean nmcommandbean, List reviewObjs) throws WTException
    {
        ArrayList list = nmcommandbean.getSelected();
        boolean flag = false;
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doRenewOperation()-----" + list.size() + " objs ared selected!");
        for (int i = 0; i < list.size(); i++)
        {
            NmContext nmcontext = (NmContext) list.get(i);
            Iterated iterated = (Iterated) nmcontext.getTargetOid().getWtRef().getObject();
            if (!iterated.isLatestIteration())
            {
                reviewObjs.remove(iterated);
                iterated = VersionControlHelper.service.getLatestIteration(iterated, false);
                reviewObjs.add(iterated);
                flag = true;
                if (VERBOSE)
                    System.out.println("doDeleteOperation   " + iterated.getIdentity() + " is renewed from reviewObjs!");
            }
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doRenewOperation()--flag=" + flag);
        return flag;
    }
}
